<?php
class ControllerCatalogTopic extends AdminController {

	public function index() {
		M('catalog/topic');
		$this->getList();
	}

	public function insert() {

		M('catalog/topic');

		if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_topic->addTopic($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/topic'));
		}

		$this->getForm();
	}

	public function update() {

		M('catalog/topic');

		if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_topic->editTopic($this->request->get['topic_id'], $this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);

			$this->redirect(UA('catalog/topic'));
		}

		$this->getForm();
	}

	public function delete() {

		M('catalog/topic');
		if (isset($this->request->post['selected'])) {
			foreach ($this->request->post['selected'] as $topic_id) {
				$this->model_catalog_topic->deleteTopic($topic_id);
			}
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/topic'));
		}
		$this->getList();
	}

	public function smartedit() {
		if ($this->hasMP()) {
			$topic_id = (int) G('id');
			$field = G('field');
			$value = G('val');
			$rs = $this->db->update('topic', array($field => $value), "topic_id = $topic_id");
		}
		else $rs = 0;
		$this->response->setOutput(json_encode(array('status' => $rs)));
	}
	
	protected function getList() {

		$this->document->setTitle($this->_['heading_title']);

		$qf = new Query_filter();
		$this->data['topics'] = $this->model_catalog_topic->getTopics($qf);
		$total = $this->model_catalog_topic->getTotalTopics();
		$this->data['pagination'] = $this->pagination($total)->render();
		
		$this->display('catalog/topic_list.tpl');
	}

	protected function getForm() {
		$this->document->setTitle($this->_['heading_title']);
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');

		$this->data['token'] = $this->session->data['token'];

		$topic_id = G('topic_id', 0);

		$this->data['modules'] = array();
		
		if ($topic_id) {
			$this->data['action'] = UA('catalog/topic/update', 'topic_id=' . $topic_id);
			if (!$this->request->isPost()) {
				$this->vo->data = $this->model_catalog_topic->getTopic($topic_id);
				$this->vo->data['topic_description'] = $this->model_catalog_topic->getTopicDescription($topic_id);
				$this->data['modules'] = $this->model_catalog_topic->getTopicModules($topic_id);
			}
		} else {
			$this->data['action'] = UA('catalog/topic/insert');
		}

		if ($this->request->isPost()) {
			$this->data['modules'] = P('module');
		}
		
		M('design/banner');
		$this->data['banners'] = $this->model_design_banner->getBanners();
		
		//languages
		$this->data['languages'] = C('cache_language_2');
		
		$this->display('catalog/topic_form.tpl');
	}
	
	protected function validateForm() {
		return true;
	}
}
?>